package com.lagou.handler;

import com.lagou.request.RpcRequest;
import com.lagou.service.UserServiceImpl;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.I0Itec.zkclient.ZkClient;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class UserServerHandler extends ChannelInboundHandlerAdapter {

    private static final Map<String, Object> serviceMap = new HashMap<>(1);
    private final ZkClient zkClient;
    private final String nodePath;

    static {
        serviceMap.put("com.lagou.service.UserService", new UserServiceImpl());
    }
    public UserServerHandler(ZkClient zkClient, String nodePath) {
        this.zkClient = zkClient;
        this.nodePath = nodePath;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        RpcRequest rpcRequest = (RpcRequest) msg;
        if (rpcRequest == null) {
            return;
        }
        String className = rpcRequest.getClassName();
        Object o = serviceMap.get(className);
        if (o == null) {
            return;
        }
//        zkClient.writeData(nodePath+"/time", System.currentTimeMillis());

        Method method = o.getClass().getDeclaredMethod(rpcRequest.getMethodName(), rpcRequest.getParameterTypes());
        Object invoke = method.invoke(o, rpcRequest.getParameters());

        ctx.writeAndFlush(invoke);
    }

}
